package com.zhj.helloframework.mvc.processer.impl;

import com.zhj.helloframework.mvc.RequestProcessorChain;
import com.zhj.helloframework.mvc.processer.RequestProcessor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;

/**
 * @Author: zhj
 * @Description: 静态资源请求处理，包括但不限于图片，css，以及js文件等, 转发到DefaultServlet
 * @Date: 2021/11/16 16:57
 * @Version: 1.0
 */
@Slf4j
public class StaticResourceRequestProcessor implements RequestProcessor {
    // 默认servlet的名称
    private static final String DEFAULT_TOMCAT_SERVLET = "default";
    // 静态资源所在目录
    private static final String STATIC_RESOURCE_PREFIX = "/static/";

    // tomcat默认请求派发器RequestDispatcher的名称
    RequestDispatcher defaultDispatcher;

    public StaticResourceRequestProcessor(ServletContext servletContext) {
        // 获取tomcat默认请求派发器
        this.defaultDispatcher = servletContext.getNamedDispatcher(DEFAULT_TOMCAT_SERVLET);
        if (this.defaultDispatcher == null) {
            throw new RuntimeException("There is no default tomcat servlet");
        }
        log.info("The default servlet for static resource is {}", DEFAULT_TOMCAT_SERVLET);
    }

    @Override
    public boolean process(RequestProcessorChain requestProcessorChain) throws Exception {
        // 1.判断请求路径判断是否是请求的静态资源 webapp/static
        if (isStaticResource(requestProcessorChain.getRequestPath())) {
            // 2.如果是静态资源，则将请求转发给default servlet处理
            defaultDispatcher.forward(requestProcessorChain.getRequest(), requestProcessorChain.getResponse());
            return false;
        }
        return true;
    }

    // 判断请求路径前缀(目录)是否为静态资源/static/
    public boolean isStaticResource(String path) {
        return path.startsWith(STATIC_RESOURCE_PREFIX);
    }
}
